/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data.email;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.mail.Folder;
import javax.mail.Part;
import connection.Account;
import connection.IMAPAccount;

/**
 * Třída reprezentující přílohu k e-mailu.
 * @author Arcanis
 */
public class Attachment {
    //@TODO dodělat

    String name;
    EmailFolder folder;
    Account account;
    Part part;

    public Attachment(String name, Part part, Account account, EmailFolder folder) {
        this.part = part;
        this.name = name;
        this.folder = folder;
    }

    public void Download(String path, String filename, boolean openConnection) throws Exception {     
        if (openConnection) {
            if (this.account instanceof IMAPAccount) {
                ((IMAPAccount)this.account).connectToStore();
            }
            this.folder.connectToFolder();
        }
        InputStream is = part.getInputStream();
        File fl = new File(path + filename);
        FileOutputStream fos = new FileOutputStream(fl);
        byte[] buf = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buf)) != -1) {
            fos.write(buf, 0, bytesRead);
        }
        fos.close();
        if (openConnection) {
            this.folder.disconnectFromFolder();
            if (this.account instanceof IMAPAccount) {
                ((IMAPAccount)this.account).disconnectFromStore();
            }
        }
    }

    public String getFileName() {
        return this.name;
    }
}
